# -*- encoding: utf-8 -*-

"""
Logging operations
"""

import logging
import logging.handlers
import os
import sys

# 日志格式
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(module)s.%(funcName)s:%(lineno)d - %(message)s'


def init(filename=None):
    for hdlr in logging.root.handlers:
        print(hdlr)
        logging.root.removeHandler(hdlr)
    # StreamHandler 日志输出到控制台
    hdlr = logging.StreamHandler()
    hdlr.setLevel(logging.INFO)
    hdlr.setFormatter(logging.Formatter(LOG_FORMAT))
    logging.root.addHandler(hdlr)
    logging.root.setLevel(logging.INFO)

    if filename is not None:
        head, tail = os.path.split(filename)
        if not os.path.exists(head):
            os.makedirs(head)
        hdlr = logging.handlers.TimedRotatingFileHandler(filename, when='D', backupCount=30)
        hdlr.setLevel(logging.INFO)
        hdlr.setFormatter(logging.Formatter(LOG_FORMAT))
        logging.root.addHandler(hdlr)
        logging.root.setLevel(logging.DEBUG)

    module = sys.modules[__name__]
    setattr(module, 'debug', logging.debug)
    setattr(module, 'info', logging.info)
    setattr(module, 'warn', logging.warning)
    setattr(module, 'error', logging.error)
    setattr(module, 'exception', logging.exception)


def debug(msg, *args, **kwargs):
    logging.debug(msg, *args, **kwargs)


def info(msg, *args, **kwargs):
    logging.info(msg, *args, **kwargs)


def warn(msg, *args, **kwargs):
    logging.warning(msg, *args, **kwargs)


def error(msg, *args, **kwargs):
    logging.error(msg, *args, **kwargs)


def exception(msg='', *args, **kwargs):
    logging.exception(msg, *args, **kwargs)


if __name__ == '__main__':
    init('../logs/datatest.log')
    info("info message")
